package com.boruan.qq.zxgylibrary;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.constants.MyApplication;
import com.boruan.qq.zxgylibrary.service.manager.GXDrugModule;
import com.boruan.qq.zxgylibrary.service.model.FirstBannerBean;
import com.boruan.qq.zxgylibrary.service.model.FirstCategoryBean;
import com.boruan.qq.zxgylibrary.service.model.InsuranceUrl;
import com.boruan.qq.zxgylibrary.service.presenter.FirstPagePresenter;
import com.boruan.qq.zxgylibrary.service.view.FirstPageView;
import com.boruan.qq.zxgylibrary.ui.activities.DrugClassifyActivity;
import com.boruan.qq.zxgylibrary.ui.activities.LocationSearchActivity;
import com.boruan.qq.zxgylibrary.ui.activities.MyOrderActivity;
import com.boruan.qq.zxgylibrary.ui.activities.SearchActivity;
import com.boruan.qq.zxgylibrary.ui.activities.ShoppingCarActivity;
import com.boruan.qq.zxgylibrary.ui.adapters.MyGridViewAdapter;
import com.boruan.qq.zxgylibrary.ui.adapters.MyViewPagerAdapter;
import com.boruan.qq.zxgylibrary.ui.widgets.ObservableScrollView;
import com.boruan.qq.zxgylibrary.utils.CustomDialogOne;
import com.boruan.qq.zxgylibrary.utils.DecoObject;
import com.boruan.qq.zxgylibrary.utils.GlideUtil;
import com.boruan.qq.zxgylibrary.utils.RequestPermissionType;
import com.convenient.qd.core.base.arouter.ARouterConstant;
import com.convenient.qd.core.bean.BaseResBean;
import com.convenient.qd.core.constant.Constant;
import com.convenient.qd.core.net.BaseHttpObserver;
import com.convenient.qd.core.user.UserDBHelper;
import com.convenient.qd.core.utils.UMEventUtil;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterConstant.ACTIVITY_DRUG_HOME)
public class MainActivity extends BaseActivity
        implements ViewPager.OnPageChangeListener,FirstPageView{

    @BindView(R2.id.first_scroll)
    ObservableScrollView firstScroll;
    @BindView(R2.id.ll_hide_show)
    LinearLayout llHideShow;
    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;
    @BindView(R2.id.ll_first_top)
    LinearLayout llFirstTop;
    @BindView(R2.id.ll_search_top)
    LinearLayout llSearchTop;
    @BindView(R2.id.ll_search)
    LinearLayout llSearch;
    @BindView(R2.id.banner_first_page)
    XBanner bannerFirstPage;
    @BindView(R2.id.viewPager)
    ViewPager viewPager;
    @BindView(R2.id.points)
    LinearLayout points;
    @BindView(R2.id.tv_location)
    TextView tvLocation;
    private WebView zbWebView;
    private CustomDialogOne customDialog;
    /** 首页轮播图片资源 */
    private List<String> mBannerUrlPath;
    /** 动态添加首页分类导航 */
    private ImageView[] ivPoints;//小圆点图片集合
    private int totalPage;//总的页数
    private int mPageSize = 10;//每页显示的最大数量
    private List<View> viewPagerList;//GridView作为一个View对象添加到ViewPager集合中
    private int currentPage;//当前页

    private FirstPagePresenter firstPagePresenter;
    private GlideUtil glideUtil;

    /** 权限申请 */
    private static String[] allpermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_main;
    }

    @Override
    public void onResume() {
        super.onResume();
        bannerFirstPage.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        bannerFirstPage.stopAutoPlay();
    }

    @Override
    protected void init(Bundle savedInstanceState) {

//        if (!NetWorkUtil.isOnline(MainActivity.this)){
//            Toast.makeText(MainActivity.this, "网络未连接，请检查网络后重试！", Toast.LENGTH_SHORT).show();
//            finish();
//            return;
//        }
        Constant.sceneId = "1201";
        SharedPreferences.Editor editor = MyApplication.getSharedreferences().edit();
        editor.putString("user",UserDBHelper.getInstance().getAccessToken());
        editor.apply();

        /** 取一下用户登录后存在本地的token */
        SharedPreferences sharedPreferences = MyApplication.getSharedreferences();
        ConstantInfo.userToken = sharedPreferences.getString("user","bearer 62cf2580-2b1b-40f3-8ce6-a7dc474c64d9");
        if (ConstantInfo.userToken.startsWith("bearer ")){
            ConstantInfo.h5UserToken = ConstantInfo.userToken.replace("bearer ","");
        }else {
            ConstantInfo.h5UserToken = ConstantInfo.userToken;
            ConstantInfo.userToken = "bearer " + ConstantInfo.userToken;
        }
        /*ConstantInfo.userToken = "bearer 7f1787d9-55ce-472c-a35b-ef7690d1f416";
        ConstantInfo.h5UserToken = "7f1787d9-55ce-472c-a35b-ef7690d1f416";*/

        Log.i("token",ConstantInfo.userToken);

        /** 获取屏幕宽高*/
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        ConstantInfo.screenWidth = displayMetrics.widthPixels;
        ConstantInfo.screenHeight = displayMetrics.heightPixels;

        glideUtil = new GlideUtil();
        customDialog = new CustomDialogOne(this,R.style.CustomDialogOne);
        customDialog.show();
        verifyStoragePermissions();

        /** 获取保存在本地的json数据 */
        String json = sharedPreferences.getString("GYJson","");
        Log.i("json",json);
        initWeb(ConstantInfo.baseUrl + "home?type=android&token=" + ConstantInfo.h5UserToken,json);

        firstPagePresenter = new FirstPagePresenter(this);

        firstPagePresenter.onCreate();
        firstPagePresenter.attachView(this);
        //firstPagePresenter.startLocation(tvLocation,2);
        /** 获取轮播图 */
        firstPagePresenter.getFirstBannerData();
        /** 获取首页分类数据 */
        firstPagePresenter.getFirstCategoryData();

        initScrollView();
        getInsuranceBalance();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (ConstantInfo.isRestart){
            firstPagePresenter.startLocation(tvLocation,2);
            ConstantInfo.isRestart = false;
        }
    }

    private void initFirstClassify(final List<FirstCategoryBean.ResultBean> data) {
        LayoutInflater inflater = LayoutInflater.from(this);
        /** 总的页数，取整（这里有三种类型：Math.ceil(3.5)=4:向上取整，只要有小数都+1  Math.floor(3.5)=3：向下取整  Math.round(3.5)=4:四舍五入）*/
        totalPage = (int) Math.ceil(data.size() * 1.0 / mPageSize);
        viewPagerList = new ArrayList<>();
        if (viewPager == null)//因为给定位权限之前会做这些操作，现在不给权限要把页面销毁，控件可能会存在空指针的情况，要判断一下。
            return;
        for (int i = 0; i < totalPage; i++){
            //每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.drug_item_layout_pager,viewPager,false);
            gridView.setAdapter(new MyGridViewAdapter(this,data,i,mPageSize));
            gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
            //添加item点击监听
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + currentPage*mPageSize;
                    Log.i("TAG","position的值为："+position + "-->pos的值为："+pos);
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, DrugClassifyActivity.class);
                    intent.putExtra("drugName",data.get(pos).getCategoryCName());
                    intent.putExtra("cId",data.get(pos).getCategoryCid());
                    startActivity(intent);
                }
            });
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView);
        }

        //设置ViewPager适配器
        viewPager.setAdapter(new MyViewPagerAdapter(viewPagerList));
        //小圆点指示器
        ivPoints = new ImageView[totalPage];
        for(int i=0;i<ivPoints.length;i++){
            ImageView imageView = new ImageView(this);
            //设置图片的宽高
            imageView.setLayoutParams(new ViewGroup.LayoutParams(10,10));
            if(i == 0){
                imageView.setBackgroundResource(R.mipmap.drug_classify_select_true);
            }else{
                imageView.setBackgroundResource(R.mipmap.drug_classify_select_false);
            }
            ivPoints[i] = imageView;
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 10;//设置点点点view的左边距
            layoutParams.rightMargin = 10;//设置点点点view的右边距
            points.addView(imageView,layoutParams);
        }
        //设置ViewPager滑动监听
        viewPager.addOnPageChangeListener(this);

    }

    private boolean isFirst = true;//控制动画标识
    private boolean isRightFirst = true;//控制向右移除动画
    /**
     * 计时器
     */
    private Handler mHandler = new Handler();
    private Runnable mRunnable;
    @SuppressLint("ClickableViewAccessibility")
    private void initScrollView() {
        firstScroll.setOnTouchListener(new View.OnTouchListener() {
            private int lastY = 0;
            private int touchEventId = -9983761;
            @SuppressLint("HandlerLeak")
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    View scroller = (View) msg.obj;
                    if (msg.what == touchEventId) {
                        if (lastY == scroller.getScrollY()) {
                            //滑动停止了
                            isRightFirst = true;
							if(llHideShow != null){
								llHideShow.setVisibility(View.VISIBLE);
                                llHideShow.setAnimation(AnimationUtils.makeInAnimation(MainActivity.this, false));
							}


                        } else {
                            handler.sendMessageDelayed(handler.obtainMessage(touchEventId, scroller), 5);
                            lastY = scroller.getScrollY();
                        }
                    }
                }
            };


            public boolean onTouch(final View v, final MotionEvent event) {

                if (mRunnable != null){
                    mHandler.removeCallbacks(mRunnable);
                }

                mRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            handler.sendMessageDelayed(handler.obtainMessage(touchEventId, v), 5);
                        }
                    }
                };
                mHandler.postDelayed(mRunnable,1000);

                /*switch (event.getAction()){
                    case MotionEvent.ACTION_UP:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("test","离开了！");
                            }
                        },2000);
                        break;
                }*/

                return false;
            }
        });

        firstScroll.setScrollViewListener(new ObservableScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                /** 这个判断条件只控制头部title的隐藏显示 */
                if (y == 0){
                    llSearchTop.setVisibility(View.GONE);
                    llFirstTop.setVisibility(View.VISIBLE);
                    llSearch.setVisibility(View.VISIBLE);
                    isFirst = true;//拉到顶部动画重置

                }else if (y > 10){
                    llSearchTop.setVisibility(View.VISIBLE);
                    llFirstTop.setVisibility(View.GONE);
                    llSearch.setVisibility(View.GONE);

                    if (isFirst){
                        llSearchTop.setAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.drug_slide_in_bottom));
                        llFirstTop.setAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.drug_slide_out_top_one));
                        isFirst = false;//上滑的时候动画只展示一次
                    }

                    if (isRightFirst){
                        llHideShow.setVisibility(View.GONE);
                        llHideShow.setAnimation(AnimationUtils.makeOutAnimation(MainActivity.this, true));
                        isRightFirst = false;
                    }

                }
            }
        });

    }

    /**
     * 初始化web
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void initCommonWeb(final String richText){
        commonWeb.loadUrl(richText);
        commonWeb.addJavascriptInterface(new DecoObject(MainActivity.this), "control");
        commonWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                customDialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                //customDialog.show();
            }
        });
        commonWeb.evaluateJavascript("window.getToken(" + ConstantInfo.userToken + ")", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.i("error",s);

            }
        });
        llAddWeb.addView(commonWeb);
    }


    /**
     * 初始化web
     */
    private void initWeb(final String richText,final String msg) {

        //初始化webView
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                zbWebView = new WebView(MainActivity.this);
                zbWebView.getSettings().setJavaScriptEnabled(true);
                zbWebView.getSettings().setSupportZoom(true);
                zbWebView.getSettings().setBuiltInZoomControls(true);
                zbWebView.getSettings().setDisplayZoomControls(false);

                zbWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                zbWebView.getSettings().setLoadWithOverviewMode(true);
                zbWebView.getSettings().setUseWideViewPort(true);
                zbWebView.getSettings().setTextZoom(100);

                zbWebView.setVerticalScrollBarEnabled(false);
                zbWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//默认先不使用缓存
                zbWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
                zbWebView.getSettings().setDefaultTextEncodingName("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    zbWebView.getSettings().setMixedContentMode(zbWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
                }
                //zbWebView.loadDataWithBaseURL(null, RichTextUtils.getHtmlData(richText), "text/html", "UTF-8", null);
                zbWebView.loadUrl(richText);
                zbWebView.addJavascriptInterface(new DecoObject(MainActivity.this), "control");
                //zbWebView.setWebViewClient(new HtmlUtils.MyWebViewClient());
                zbWebView.setWebViewClient(new WebViewClient(){
                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                    @Override
                    public void onPageFinished(WebView view, String url) {
						if (MainActivity.this.isFinishing() || MainActivity.this == null) {
                            return;
                        }
                        super.onPageFinished(view, url);
                        zbWebView.evaluateJavascript("window.receiveData(" + msg + ")", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String s) {
                                Log.i("error",s);
                            }
                        });
                        firstPagePresenter.startLocation(tvLocation,2);
                    }

                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
						if (MainActivity.this.isFinishing() || MainActivity.this == null) {
                            return;
                        }
                        super.onPageStarted(view, url, favicon);
                        //customDialog.show();
                    }

                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.proceed();//接受所有网站的证书，忽略SSL错误
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                        super.onReceivedError(view, webResourceRequest, webResourceError);
                        if (webResourceRequest.isForMainFrame()) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
//                            Toast.makeText(MainActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
//                            finish();
                        }
                    }

                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                        super.onReceivedError(view, errorCode, description, failingUrl);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            return;
                        }
//                        view.loadUrl("about:blank");// 避免出现默认的错误界面
//                        Toast.makeText(MainActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
//                        finish();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                        super.onReceivedHttpError(view, request, errorResponse);
                        // 这个方法在 android 6.0才出现
                        int statusCode = errorResponse.getStatusCode();
                        if (404 == statusCode || 500 == statusCode) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
//                            Toast.makeText(MainActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
//                            finish();
                        }
                    }
                });

				if(llAddWeb != null ){
					llAddWeb.addView(zbWebView);
				}

            }
        }, 100);

    }

    private void getInsuranceBalance() {
        GXDrugModule.getInstance().getInsuranceBalance(new BaseHttpObserver<BaseResBean<InsuranceUrl>>() {
            @Override
            public void onSuccess(BaseResBean<InsuranceUrl> res) {
                ConstantInfo.ybBalance =res.getResult().getContent();

            }

            @Override
            public void onFailure(int status, String msg) {
                ConstantInfo.ybBalance ="";
            }
        });
    }

    @OnClick({R2.id.tv_location,R2.id.iv_back,R2.id.ll_search_top, R2.id.ll_search, R2.id.tv_pfyy, R2.id.tv_gmfs, R2.id.tv_ksyy, R2.id.tv_cwyy, R2.id.tv_etyy, R2.id.tv_qwbs, R2.id.tv_qrjd, R2.id.tv_fkyy, R2.id.tv_nkyy, R2.id.tv_jtbb, R2.id.iv_order, R2.id.iv_shopping_cart})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        int i = view.getId();
        if (i == R.id.tv_location) {
            UMEventUtil.onEventObject(this,"1201004","");
            intent.setClass(MainActivity.this, LocationSearchActivity.class);
            intent.putExtra("city","青岛市");
            startActivityForResult(intent,20);

        } else if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.ll_search_top) {
            UMEventUtil.onEventObject(this,"1201005","");
            intent.setClass(MainActivity.this, SearchActivity.class);
            startActivity(intent);

        } else if (i == R.id.ll_search) {
            intent.setClass(MainActivity.this, SearchActivity.class);
            startActivity(intent);

        } else if (i == R.id.iv_order) {
            UMEventUtil.onEventObject(this,"1201019","");
            intent.setClass(MainActivity.this, MyOrderActivity.class);
            startActivity(intent);

        } else if (i == R.id.iv_shopping_cart) {
            UMEventUtil.onEventObject(this,"1201020","");
            intent.setClass(MainActivity.this, ShoppingCarActivity.class);
            startActivity(intent);

        }

    }

    private void verifyStoragePermissions(){
        /** 添加6.0以上读写权限和定位权限 */
        if(Build.VERSION.SDK_INT >= 23){
            boolean needApply = false;
            for(int i = 0; i < allpermissions.length;i++){
                int checkPermission= ContextCompat.checkSelfPermission(MainActivity.this,
                        allpermissions[i]);
                if(checkPermission!= PackageManager.PERMISSION_GRANTED){
                    needApply=true;
                }
            }
            if(needApply){
                ConstantInfo.isDialogShow = false;
                ActivityCompat.requestPermissions(MainActivity.this,allpermissions,RequestPermissionType.REQUEST_CODE_LOCATION);
            }
        }
    }


    /** 定位回调 */
    public void  onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RequestPermissionType.REQUEST_CODE_LOCATION){
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    if (firstPagePresenter != null){
                        firstPagePresenter.startLocation(tvLocation,2);
                    }
                } else {
                    customDialog.dismiss();
                    Toast.makeText(this, "定位权限没有开启，请在设置中打开哦！", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //改变小圆圈指示器的切换效果
        setImageBackground(position);
        currentPage = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 改变指示器切换效果
     * */
    private void setImageBackground(int selectItems) {
        for (int i = 0; i < ivPoints.length; i++) {
            if (i == selectItems) {
                ivPoints[i].setBackgroundResource(R.mipmap.drug_classify_select_true);
            } else {
                ivPoints[i].setBackgroundResource(R.mipmap.drug_classify_select_false);
            }
        }
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void getFirstBannerDataSuccess(List<FirstBannerBean.ResultBean> firstBannerBean) {
        mBannerUrlPath = new ArrayList<>();
        for (int i = 0;i < firstBannerBean.size();i++){
            mBannerUrlPath.add(firstBannerBean.get(i).getImage());
        }

        /** 轮播图 */
        if (bannerFirstPage == null)
            return;
        bannerFirstPage.setData(mBannerUrlPath, null);
        bannerFirstPage.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, int position) {

            }
        });

        bannerFirstPage.setmAdapter(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ImageView imgBanner = (ImageView)view;
                imgBanner.setScaleType(ImageView.ScaleType.FIT_XY);
                imgBanner.setAdjustViewBounds(true);
                glideUtil.attach(imgBanner).injectImageWithNull(mBannerUrlPath.get(position));
                //ImageLoader.loadImg(MainActivity.this,mBannerUrlPath.get(position),R.mipmap.ic_launcher_round,(ImageView) view);

            }
        });
    }

    @Override
    public void getFirstBannerDataFailed(String msg) {
        if(TextUtils.isEmpty(msg)){
            return;
        }
        if (customDialog != null){
            if (!MainActivity.this.isFinishing()){
                customDialog.dismiss();
            }
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void getFirstCategoryDataSuccess(List<FirstCategoryBean.ResultBean> firstCategoryBean) {
        initFirstClassify(firstCategoryBean);
    }

    @Override
    public void getFirstCategoryDataFailed(String msg) {
        if(TextUtils.isEmpty(msg)){
            return;
        }
        if (customDialog != null){
            if (!MainActivity.this.isFinishing()){
                customDialog.dismiss();
            }
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void saveLocationSuccess(String msg) {
        SharedPreferences.Editor editor = MyApplication.getSharedreferences().edit();
        editor.putString("GYJson",msg);
        editor.commit();
        Log.i("msg","上传成功！");

        if (zbWebView == null)
            return;
        zbWebView.evaluateJavascript("window.receiveData(" + msg + ")", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.i("error",s);
            }
        });

        if (customDialog != null){
            if (!MainActivity.this.isFinishing()){
                customDialog.dismiss();
            }

        }
    }

    @Override
    public void saveLocationFailed(String msg) {
        if(TextUtils.isEmpty(msg)){
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        if (customDialog != null){
            if (!MainActivity.this.isFinishing()){
                customDialog.dismiss();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20 && resultCode == 22){
            ConstantInfo.lat = data.getDoubleExtra("lat",0);
            ConstantInfo.lng = data.getDoubleExtra("lon",0);
            ConstantInfo.mDistrict = data.getStringExtra("address");
            tvLocation.setText(ConstantInfo.mDistrict);

            customDialog.show();
            //llAddWeb.removeAllViews();
            firstPagePresenter.updateLocationOne(String.valueOf(ConstantInfo.lat),String.valueOf(ConstantInfo.lng));
        }
    }

    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (zbWebView != null) {
            //加载null内容
            zbWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            zbWebView.clearHistory();
            //移除WebView
            ((ViewGroup) zbWebView.getParent()).removeView(zbWebView);
            //销毁VebView
            zbWebView.destroy();
            //WebView置为null
            zbWebView = null;
        }
        super.onDestroy();
    }
}
